package org.arch_learn.netty_rpc.consumer.processor;

import org.arch_learn.netty_rpc.consumer.anno.RpcReference;
import org.arch_learn.netty_rpc.consumer.proxy.NettyRpcClientProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Optional;

@Component
public class RpcReferenceBeanProcessor implements BeanPostProcessor {
    @Autowired
    private NettyRpcClientProxy nettyRpcClientProxy;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field f : declaredFields) {
            Optional.ofNullable(f.getAnnotation(RpcReference.class))
                    .ifPresent(v -> {
                        Class<?> fieldType = f.getType();
                        Object proxyObject = nettyRpcClientProxy.createProxy(fieldType);
                        f.setAccessible(true);
                        try {
                            f.set(bean, proxyObject);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                            System.out.println("实例属性：" + f.getName()+"注入失败！");
                        }
                    });
        }
        return bean;
    }
}
